package enterprise

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"insighttracking/query/dao"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type DeleteEnterpriseByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewDeleteEnterpriseByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *DeleteEnterpriseByIdApiLogic {
	hostname, _ := os.Hostname()
	return &DeleteEnterpriseByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *DeleteEnterpriseByIdApiLogic) DeleteEnterpriseByIdApi(req *types.IdReq) (resp string, err error) {
	// 企业下有门店不能直接删除
	_, err = dao.EnterpriseCustomerEntity.WithContext(l.ctx).Where(dao.EnterpriseCustomerEntity.EnterpriseID.Eq(req.Id)).First()
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("当前企业下有门店,不能直接删除")
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	// 删除登录账号
	if err = service.AccountService.DeleteByEnterpriseIdApi(l.ctx, tx, req.Id); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("删除失败")
	}
	// 删除员工信息
	if err = service.EnterprisePersonService.DeleteByEnterpriseIdApi(l.ctx, tx, req.Id); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("删除失败")
	}
	// 删除门店
	if err = service.EnterpriseCustomerService.DeleteByEnterpriseIdApi(l.ctx, tx, req.Id); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("删除失败")
	}
	// 删除企业
	if err = service.EnterpriseService.DeleteByIdApi(l.ctx, tx, req.Id); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("删除失败")
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("删除失败")
	}
	return "删除成功", nil
}
